﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VideoCache.Server.Areas.Api.Models;
using VideoCache.Server.BLL;
using VideoCache.Server.Model;
using VideoCache.Server.MVCWeb.Areas.Api.Models;
using VideoCache.Security;

namespace VideoCache.Server.MVCWeb.Areas.Api.Controllers
{
    public class SyncController : Controller
    {
        //
        // GET: /Api/Sync/

        public ActionResult Index()
        {
            SyncModel model = this.GetSyncModel();

            SecurityResponseModel responseModel = new SecurityResponseModel(model);

            return Json(responseModel, JsonRequestBehavior.AllowGet);
        }

        [NonAction]
        private SyncModel GetSyncModel()
        {
            SyncModel model = new SyncModel();
            model.DictionaryList.AddRange(DictionaryBLL.FindAll(null, null));

            List<AlbumInfo> albumList = AlbumBLL.FindAll(null, null);
            List<EpisodeInfo> episodeList = EpisodeBLL.FindAll(null, null);

            foreach (AlbumInfo info in albumList)
            {
                SyncAlbumModel album = new SyncAlbumModel
                {
                    Id = info.Id,
                    Title = info.Title,
                    PubYear = info.PubYear,
                    TypeId = info.TypeId,
                    AreaId = info.AreaId,
                    Priority = info.Priority,
                    Rating = info.Rating,
                    Status = info.Status,
                    IsEnd = info.IsEnd > 0,
                    ModifyTime = info.ModifyTime
                };

                foreach (EpisodeInfo episode in episodeList.FindAll(p => p.AlbumId == album.Id))
                {
                    SyncEpisodeModel episodeModel = new SyncEpisodeModel
                    {
                        Episode = episode.EpisodeIndex,
                        AlbumId = episode.AlbumId,
                        Name = episode.Name,
                        ModifyTime = episode.ModifyTime
                    };

                    album.Episodes.Add(episodeModel);
                }

                model.AlbumList.Add(album);
            }

            return model;
        }
    }
}
